package com.lord.wand.common;

import java.io.Serializable;
import java.util.Date;
import java.util.UUID;

import org.hibernate.EmptyInterceptor;
import org.hibernate.type.Type;

/**
 * hibernate 拦截器 通用字段赋值
 * 
 * @author xuyh
 *
 */
//@Component
public class EntityEmptyInterceptor extends EmptyInterceptor {

	/**
	 * 
	 */
	private static final long serialVersionUID = 4309422314499256850L;

	@Override
	public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) {
		return updateEntity(entity, state, propertyNames);
	}

	private boolean updateEntity(Object entity, Object[] state, String[] propertyNames) {
		boolean modified = false;
		// if (entity instanceof EntityOwner) {
		for (int i = 0; i < propertyNames.length; i++) {
			if (state[i] == null) {
				String propertyName = propertyNames[i];
				if ("guid".equals(propertyName)) {
					state[i] = UUID.randomUUID().toString().replaceAll("-", "");
					modified = true;
				} else if ("creator".equals(propertyName)) {
					// Member creator = loginService.getDbLoginUser();
					// state[i] = creator;
					// modified = true;
				} else if ("createTime".equals(propertyName)) {
					state[i] = new Date();
					modified = true;
				}
			}
		}
		// }
		return modified;
	}

}
